package agan.rpc.protocol;

import agan.rpc.register.LocalRegister;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;
public class HttpServerHandler {
    public void handler(HttpServletRequest request, HttpServletResponse response){
        try {
            // 获取客户端传过来的Invocation消息
            Invocation invocation = (Invocation) new ObjectInputStream(request.getInputStream()).readObject();
            String interfaceName = invocation.getInterfaceName();
            String methodName = invocation.getMethodName();
            // 根据接口名称，获取想要调用的实现类
            Class clazz = LocalRegister.get(interfaceName);
            Method method = clazz.getMethod(methodName, invocation.getTypes());
            // 利用反射执行消费者想要调用的方法
            String result = (String)method.invoke(clazz.newInstance(), invocation.getArgs());
            // 返回方法的执行结果
            IOUtils.write(result, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
